#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <cstdlib>
#include <cstdint>
#include <cstring>

using namespace std;

class Solution {
public:
    int myAtoi(string str) {
        if (str.length() == 0){
            return 0;
        }
        int i = 0;
        int state = 0;
        int flag = 1;
        long long num = 0;
        int loop = 1;
        while (i < str.length() && (str[i] == ' ' || str[i] == '\t' )) i++;
        for (;i < str.length() && loop;i++){
            switch (state)
            {
            case 0:
                if ('+' == str[i]){
                    flag = 1;
                }else if ('-' == str[i]){
                    flag = -1;
                }else if ('0' <= str[i] && str[i] <= '9'){
                    num += num * 10 + str[i] - '0';
                }else{
                    return 0;
                }
                state++;
                break;
            case 1:
                if ('0' <= str[i] && str[i] <= '9'){
                    // printf("num*10 is %d,", num*10);
                    num = num * 10 + (str[i] - '0');
                    // printf("str[i] is %c, str[i]-'0' is %d, num is %d\r\n", str[i], str[i]-'0', num);
                    if (num > INT_MAX){
                        loop = 0;
                    }
                }else{
                    loop = 0;
                }
                break;
            default:
                break;
            }
        }
        num *= flag;
        if (num >= INT_MAX){
            return INT_MAX;
        }else if (num <= INT_MIN){
            return INT_MIN;
        }else{
            return num;
        }
    }
};

int main(void)
{
    string s = "-0032324aa";
    int result;
    Solution su;
    result = su.myAtoi(s);
    printf("result is %d\r\n", result);
    return 0;
}
